package queue;

import seque.SequeList;
import stack.Stack;
import stack.StackLink;

import javax.swing.plaf.InsetsUIResource;
import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.Deque;

/**
 * @author niann
 * @description  双端队列————基于数组实现
 * 队列:  -> -> -> -> -> -> ->             左进右出
 * 双端队列: 两边都可以进行入队和出队
 * @since 2024/8/28 下午4:37
 **/
public class Queue<E> implements StackLink<E> {


    private Object [] datas=new Object[10];
    private  int size=0;


    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size==0;
    }

    @Override
    public void clear() {
        datas= new Object[10];
    }

    public void scale(){
        var newArr=new Object[datas.length*2];
        System.arraycopy(datas,0,newArr,0,size);
        datas=newArr;
    }

    /**
     * 从头部插入元素
     * @param e
     */
    @Override
    public void push(E e) {
        if (datas.length>=size){
            scale();
        }
        for (int i = size; i >0 ; i--) {
            datas[i]=datas[i-1];
        }
        datas[0]=e;
        size++;
    }

    /**
     * 从尾部取出元素
     * @return
     */
    @Override
    public E pop() {
        if (size==0){
            throw new RuntimeException("队列为空");
        }
        E data = (E) datas[size-1];
        datas[size-1]=null;
        size--;
        return  data;
    }

    /**
     * 从头部取出元素
     * @return
     */
    public E peek(){
        if (isEmpty()){
            throw new RuntimeException("队列为空");
        }
        var data = (E) datas[0];
        for (int i = 0; i < size-1; i++) {
            datas[i]=datas[i+1];
        }
        return data;
    }

    /**
     * 从尾部插入元素
     * @param e
     */
    public void offer(E e){
        if (datas.length>=size){
            scale();
        }
        datas[size]=e;
        size++;
    }

    @Override
    public String toString() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("[");
        for (int i = 0; i < size; i++) {
            stringBuilder.append(datas[i]).append(",");
        }
        if (!isEmpty()){
            stringBuilder.deleteCharAt(stringBuilder.length()-1);
        }
        stringBuilder.append("]");
        return stringBuilder.toString();
    }
}
